<template>
  <div class="search">
    <form action="/">
      <van-search
        v-model.trim="value"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="$router.back()"
        @focus="isShowRes=false"
      />
    </form>
    <search-results v-if="isShowRes" :searchText="value"/>
    <search-history @allDel="allDel" @search="onSearch" v-else-if="!value" :history="history" />
    <search-suggestion @search="onSearch" :searchText='value' v-else />
  </div>
</template>

<script>
import { setStorage, getStorage } from '@/utils/storage.js'
import SearchHistory from './components/SearchHistory.vue'
import SearchSuggestion from './components/SearchSuggestion.vue'
import SearchResults from './components/SearchResults.vue'
export default {
  components: { SearchHistory, SearchSuggestion, SearchResults },
  name: 'Search',
  data () {
    return {
      value: '',
      isShowRes: false,
      history: getStorage('TT_History') || []
    }
  },

  created () {
  },

  watch: {
    history: {
      deep: true,
      handler () {
        setStorage('TT_History', this.history)
      }
    }
  },

  methods: {
    onSearch (val) {
      this.value = val
      this.isShowRes = true
      // const index = this.history.indexOf(val)
      // if (index !== -1) this.history.splice(index, 1)
      // this.history.unshift(val)
      this.history.unshift(val)
      this.history = [...new Set(this.history)]
    },
    allDel () {
      this.history = []
    }
  }
}
</script>

<style scoped lang="less">
.search {
  .van-search__action {
    color: #fff;
  }
}
</style>
